# LLM Gateway Makefile
BINARY_NAME := llm-gateway
MAIN_PATH := ./cmd
VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
LDFLAGS := -ldflags "-s -w -X main.Version=$(VERSION)"
BUILD_DIR := bin

# Colors
GREEN := \033[0;32m
BLUE := \033[0;34m
YELLOW := \033[0;33m
RESET := \033[0m

.PHONY: help build run test clean fmt deps migrate create-user create-admin

help: ## Show available commands
	@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf "  $(GREEN)%-12s$(RESET) %s\n", $$1, $$2}' $(MAKEFILE_LIST)

build: ## Build binary
	@echo "$(BLUE)Building $(BINARY_NAME)...$(RESET)"
	@mkdir -p $(BUILD_DIR)
	go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME) $(MAIN_PATH)
	@echo "$(GREEN)Built: $(BUILD_DIR)/$(BINARY_NAME)$(RESET)"

build-linux: ## Build binary for Linux
	@echo "$(BLUE)Building $(BINARY_NAME) for Linux...$(RESET)"
	@mkdir -p $(BUILD_DIR)
	GOOS=linux GOARCH=amd64 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY_NAME)-linux $(MAIN_PATH)
	@echo "$(GREEN)Built: $(BUILD_DIR)/$(BINARY_NAME)-linux for Linux$(RESET)"

run: build ## Start server
	./$(BUILD_DIR)/$(BINARY_NAME) start

test: ## Run tests
	go test -v ./...

clean: ## Clean build artifacts
	go clean
	rm -rf $(BUILD_DIR)

fmt: ## Format and lint code
	go fmt ./...
	go vet ./...

deps: ## Tidy dependencies
	go mod tidy

migrate: build ## Run database migration
	./$(BUILD_DIR)/$(BINARY_NAME) migrate

create-user: build ## Create user (make create-user user1 password123)
	@if [ -z "$(word 2,$(MAKECMDGOALS))" ] || [ -z "$(word 3,$(MAKECMDGOALS))" ]; then \
		echo "$(YELLOW)Usage: make create-user <用户名> <密码>$(RESET)"; \
		exit 1; \
	fi
	./$(BUILD_DIR)/$(BINARY_NAME) create-user $(word 2,$(MAKECMDGOALS)) $(word 3,$(MAKECMDGOALS))

create-admin: build ## Create admin (make create-admin admin password123)
	@if [ -z "$(word 2,$(MAKECMDGOALS))" ] || [ -z "$(word 3,$(MAKECMDGOALS))" ]; then \
		echo "$(YELLOW)Usage: make create-admin <用户名> <密码>$(RESET)"; \
		exit 1; \
	fi
	./$(BUILD_DIR)/$(BINARY_NAME) create-admin $(word 2,$(MAKECMDGOALS)) $(word 3,$(MAKECMDGOALS))

%:
	@:

version: ## Show version
	@echo $(VERSION)

deploy: build-linux ## Deploy to remote server
	@echo "$(BLUE)Deploying $(BINARY_NAME) to remote server...$(RESET)"
	@bash deployment/deploy.sh

.DEFAULT_GOAL := help